const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const process = require('process');
const csv = require('csv-parser');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;

router.get('/', function (req, res) {
  res.redirect('/static/index.html');
});

router.get('/input-data', (req, res) => {
  const dirPath = path.join(process.cwd(), 'public', 'input_data');
  const dataList = fs.readdirSync(dirPath);
  res.json({ dataList });
});

router.post('/input-data', (req, res) => {
  const publicPath = path.join(process.cwd(), 'public');
  const inputPath = path.join(publicPath, 'input_data', req.body.name);
  fs.writeFileSync(path.join(publicPath, 'input_path.txt'), inputPath);
  fs.copyFileSync(
    path.join(publicPath, `output_${req.body.name}`),
    path.join(publicPath, 'output.csv')
  );

  const standardData = [];
  fs.createReadStream(inputPath)
    .pipe(csv({ headers: false, skipLines: 1 }))
    .on('data', (row) => {
      // 读取最后一行
      const lastColumnValue = row[Object.keys(row).length - 1];
      standardData.push({ result: lastColumnValue });
    })
    .on('end', () => {
      // 创建新的CSV文件
      const csvWriter = createCsvWriter({
        path: path.join(publicPath, 'standard.csv'),
        header: [{ id: 'result', title: 'result' }],
      });
      csvWriter.writeRecords(standardData);

      res.json({ message: 'ok' });
    });
});

router.get('/photo-list', (req, res) => {
  const dirPath = path.join(process.cwd(), 'public', 'photo');
  const nameList = fs.readdirSync(dirPath);
  const dataList = nameList.map((item) => {
    return {
      name: item,
      src: `/static/photo/${item}`,
    };
  });
  res.json({ dataList });
});

router.get('/video-list', (req, res) => {
  const dirPath = path.join(process.cwd(), 'public', 'video');
  const nameList = fs.readdirSync(dirPath);
  const dataList = nameList.map((item) => {
    return {
      name: item,
      src: `/static/video/${item}`,
    };
  });
  res.json({ dataList });
});

router.get('/output', (req, res) => {
  const publicPath = path.join(process.cwd(), 'public');
  const standard = [];
  const output = [];

  const calcAccuracy = () => {
    if (standard.length !== output.length) return 0;
    let count = 0;
    for (let i = 0; i < standard.length; i++) {
      if (standard[i] === output[i]) count++;
    }
    return count / standard.length;
  };

  new Promise((resolve) => {
    let finishedCount = 0;
    fs.createReadStream(path.join(publicPath, 'standard.csv'))
      .pipe(csv())
      .on('data', (row) => {
        standard.push(row['result']);
      })
      .on('end', () => {
        finishedCount++;
        if (finishedCount === 2) resolve(calcAccuracy());
      });
    fs.createReadStream(path.join(publicPath, 'output.csv'))
      .pipe(csv({ headers: false }))
      .on('data', (row) => {
        output.push(row['0']);
      })
      .on('end', () => {
        finishedCount++;
        if (finishedCount === 2) resolve(calcAccuracy());
      });
  }).then((accuracy) => res.json({ standard, output, accuracy }));
});

module.exports = router;
